from datetime import datetime
from decimal import Decimal
from PySide6.QtWidgets import QVBoxLayout, QHBoxLayout, QGridLayout, QDialog, QWidget, QGroupBox, QLabel, QTableWidget
from PySide6.QtCore import Qt
from .widgets.table_widget import CommonTableWidget
from .widgets.dialogs import BaseDialog, MessageOverlay
from .widgets.panels import BasePanel
from .widgets.basewidgets import *
from api import api
from common import config, utils

PURCHASE_HEADER_COLUMNS = {"采购单号":{"type":"text", "width": 150, "text": lambda x: x["code"], "width": 0.15},
                  "供应商":{"type":"text", "text": lambda x: x["supplier"]["name"]},
                  "商品名称":{"type":"text", "text": lambda x: f'{x["items"][0]["product"]["name"] if x["items"] else ""}{("(等)" if len(x["items"]) > 1 else "")}'},
                  "数量":{"type":"text", "text": lambda x: sum([item["quantity"] for item in x["items"]]), "width": 0.08, "sort": "quantity"},
                  "总金额":{"type":"text", "text": lambda x: x["total_price"], "width": 0.1, "sort": "total_price"},
                  "状态":{"type":"text", "text": lambda x: utils.PurchaseStatus(x["status"]).description, "width": 0.08},
                  "开单时间":{"type":"text", "text": lambda x: utils.format_datetime(x["created_at"], "%Y-%m-%d")},
                  "退货":{"type":"text",
                            "text": lambda x: "有" if x["purchaseReturns"] else "无",
                            "color": lambda x: "red" if x["purchaseReturns"] else "",
                            "width": 0.05},
                  "操作":{"type":"action", "width": 0.18}}

PURCHASE_ITEMS_HEADER_COLUMNS = {"商品名称":{"type":"text", "text": lambda x: x["product"]["name"]},
                                  "数量":{"type":"text", "text": lambda x: x["quantity"]},
                                  "进货价":{"type":"text", "text": lambda x: x["cost_price"]},
                                  "总金额":{"type":"text", "text": lambda x: x["total_price"]},
                                  "操作":{"type":"action"}}

PURCHASE_RETURN_ITEMS_HEADER_COLUMNS = {"商品名称":{"type":"text", "text": lambda x: x["product"]["name"]},
                                        "数量":{"type":"text", "text": lambda x: x["quantity"]},
                                        "单价":{"type":"text", "text": lambda x: x["unit_price"]},
                                        "已退数量":{"type":"text", "text": lambda x: x["quantity_returned"]},
                                        "退货数量":{"type":"spinbox"},
                                        "退货金额":{"type":"text", "text": lambda x: x["return_price"]}}

class PurchasePage(BasePanel):
    def __init__(self):
        super().__init__("采购管理")
        self.suppliers = []
        self.setup_ui()
        self.setup_context_menu()
        
    def setup_ui(self):
        # 使用BasePanel中的main_layout而不是创建新的布局
        
        # 搜索和操作区域
        search_widget = SearchPanel()
        search_layout = QHBoxLayout(search_widget)

        # 搜索类型
        self.search_type_combo = NormalComboBox()
        self.search_type_combo.setItems({"搜单号":1, "搜商品":2})
        self.search_type_combo.currentIndexChanged.connect(self.change_search_type)

        # 搜索框
        self.search_input = SearchLineEdit()
        self.search_input.setPlaceholderText("根据采购单号搜索")
        self.search_input.textChanged.connect(self.flush_table)

        # 过滤商品
        self.product_input = AutoCompleteLineEdit(self.get_product_list, placeholder_text="搜索商品名称或编码")
        self.product_input.setVisible(False)
        self.product_input.selectedChanged.connect(self.flush_table)

        # 供货商
        self.supplier_input = NormalComboBox()
        self.supplier_input.currentIndexChanged.connect(self.flush_table)
        
        # 状态下拉框
        self.status_combo = NormalComboBox()
        self.status_combo.setItems({"全部状态": "",
                                "待审核": utils.PurchaseStatus.UNAUDITED,
                                "已审核": utils.PurchaseStatus.AUDITED,
                                "已入库": utils.PurchaseStatus.RECEIVED})
        self.status_combo.currentIndexChanged.connect(self.flush_table)

        # 时间范围选择
        self.date_range_picker = DateRangeEdit(placeholder_text="不限时间范围")
        self.date_range_picker.onRangeChanged.connect(self.flush_table)

        # 添加采购单按钮
        self.add_purchase_btn = BluePushButton("采购开单")
        self.add_purchase_btn.clicked.connect(self.show_add_purchase_dialog)

        search_layout.addWidget(self.search_type_combo)
        search_layout.addWidget(self.search_input)
        search_layout.addWidget(self.product_input)
        search_layout.addWidget(self.supplier_input)
        search_layout.addWidget(self.status_combo)
        search_layout.addWidget(self.date_range_picker)
        search_layout.addStretch()
        search_layout.addWidget(self.add_purchase_btn)

        self.main_layout.addWidget(search_widget)
        
        # 采购单表格
        table_widget = QWidget()
        table_widget.setObjectName("purchaseTable")
        table_layout = QVBoxLayout(table_widget)
        
        self.purchase_table = CommonTableWidget(headers=PURCHASE_HEADER_COLUMNS)
        self.purchase_table.set_description("采购单流程: 开单(待审核) -> 审核(已审核) -> 入库(已入库)，"
                                            "审核一旦通过该采购单将不能修改，"
                                            "只有入库的采购单才开具退单。")
        self.purchase_table.pageSizeChanged.connect(self.flush_table)
        self.purchase_table.sortChanged.connect(self.flush_table)
        
        table_layout.addWidget(self.purchase_table)
        self.main_layout.addWidget(table_widget)

    def setup_context_menu(self):
        super().setup_context_menu()
        self.purchase_table.setContextMenuPolicy(Qt.CustomContextMenu)
        self.purchase_table.customContextMenuRequested.connect(self.show_context_menu)

    def add_extra_context_menus(self, menu, pos):
        menu.addSeparator()
        add_purchase_action = menu.addAction("采购开单")
        add_purchase_action.triggered.connect(self.show_add_purchase_dialog)
        
        # 如果是在表格中点击
        sender = self.sender()
        if sender == self.purchase_table and self.purchase_table.itemAt(pos):
            row = self.purchase_table.itemAt(pos).row()
            purchase_data = self.purchase_table.get_row_data(row)
            
            menu.addSeparator()
            
            # 采购单操作子菜单
            operations_menu = menu.addMenu("采购单操作")
            
            # 根据状态添加不同的操作
            if purchase_data["status"] == utils.PurchaseStatus.UNAUDITED:
                operations_menu.addAction("审核").triggered.connect(
                    lambda: self.update_purchase_status(row, utils.PurchaseStatus.AUDITED))
                operations_menu.addAction("编辑").triggered.connect(
                    lambda: self.edit_purchase(row))
                delete_action = operations_menu.addAction("删除")
                delete_action.triggered.connect(lambda: self.delete_purchase(row))
            elif purchase_data["status"] == utils.PurchaseStatus.AUDITED:
                operations_menu.addAction("入库").triggered.connect(
                    lambda: self.update_purchase_status(row, utils.PurchaseStatus.RECEIVED))
                operations_menu.addAction("查看").triggered.connect(
                    lambda: self.edit_purchase(row))
            elif purchase_data["status"] == utils.PurchaseStatus.RECEIVED:
                operations_menu.addAction("退货").triggered.connect(
                    lambda: self.return_purchase(row))
                operations_menu.addAction("查看").triggered.connect(
                    lambda: self.edit_purchase(row))
            
            menu.addSeparator()
            
            # 采购单信息子菜单
            info_menu = menu.addMenu("采购单信息")
            info_menu.addAction(f"采购单号: {purchase_data['code']}")
            info_menu.addAction(f"供应商: {purchase_data['supplier']['name']}")
            info_menu.addAction(f"状态: {utils.PurchaseStatus(purchase_data['status']).description}")
            info_menu.addAction(f"总金额: ￥{purchase_data['total_price']}")
            info_menu.addAction(f"创建时间: {utils.format_datetime(purchase_data['created_at'])}")
            if purchase_data["updated_at"]:
                info_menu.addAction(f"更新时间: {utils.format_datetime(purchase_data['updated_at'])}")

    def change_search_type(self):
        self.search_input.setVisible(self.search_type_combo.currentData() == 1)
        self.product_input.setVisible(self.search_type_combo.currentData() == 2)

    def edit_purchase(self, row):
        # 获取当前行数据
        purchase_data = self.purchase_table.get_row_data(row)
        if purchase_data:
            dialog = AddPurchaseDialog(self, purchase_data["code"], self.suppliers)
            if dialog.exec() == QDialog.Accepted and dialog.purchase_data and \
                    dialog.purchase_data["status"] == utils.PurchaseStatus.UNAUDITED:
                api.update_purchase_items(purchase_data["code"], dialog.purchase_items)
                MessageOverlay.info(self, "采购单编辑成功")
                self.flush_table()
    
    def delete_purchase(self, row):
        if MessageOverlay.question(self, "确定要删除这个采购单吗？删除后将不能恢复。") == MessageOverlay.ACCEPTED:
            api.delete_purchase(self.purchase_table.get_row_data(row)["code"])
            MessageOverlay.info(self, "采购单删除成功")
            self.flush_table()
    
    def return_purchase(self, row):
        purchase_data = self.purchase_table.get_row_data(row)
        if purchase_data["status"] == utils.PurchaseStatus.RECEIVED:
            dialog = ReturnPurchaseDialog(self, purchase_data["code"])
            if dialog.exec() == QDialog.Accepted:
                api.add_purchase_return(purchase_data["id"], 1, dialog.return_items, dialog.reason)
                MessageOverlay.info(self, "采购退货成功")
                self.flush_table()
        else:
            MessageOverlay.warning(self, "只有已入库的采购单才能退货")
    
    def show_add_purchase_dialog(self):
        dialog = AddPurchaseDialog(self, suppliers=self.suppliers)
        if dialog.exec() == QDialog.Accepted:
            #TODO: 用户id
            api.add_purchase(dialog.supplier_id, 1, dialog.purchase_items)
            MessageOverlay.info(self, "采购单添加成功")
            self.flush_table()

    def get_product_list(self, keyword):
        if keyword:
            return api.get_products(keyword)["items"]
        else:
            self.flush_table()
            return []
        
    def flush_table(self):
        selected_product = self.product_input.get_selected_item()
        purchases = api.get_purchases(code=self.search_input.text(),
                                      product_id=selected_product["id"] if selected_product else None,
                                      supplier_id=self.supplier_input.currentData(),
                                      status=self.status_combo.currentData(),
                                      page=self.purchase_table.current_page,
                                      per_page=self.purchase_table.page_size,
                                      order_by=self.purchase_table.sort_string,
                                      range_date=self.date_range_picker.get_range())
        if not purchases:
            return
        self.purchase_table.clearContents()
        self.purchase_table.setRowCount(0)
        self.purchase_table.set_total_items(purchases["count"])
        row_count = len(purchases["items"])
        self.purchase_table.setRowCount(row_count)
        for i in range(row_count):
            if purchases["items"][i]["status"] == utils.PurchaseStatus.UNAUDITED:
                action_buttons = [{"text": "审核", "callback": lambda row, status=utils.PurchaseStatus.AUDITED: self.update_purchase_status(row, status)}]
            elif purchases["items"][i]["status"] == utils.PurchaseStatus.AUDITED:
                action_buttons = [{"text": "入库", "callback": lambda row, status=utils.PurchaseStatus.RECEIVED: self.update_purchase_status(row, status)}]
            elif purchases["items"][i]["status"] == utils.PurchaseStatus.RECEIVED:
                action_buttons = [{"text": "退货", "callback": self.return_purchase}]
            else:
                action_buttons = []
            self.purchase_table.set_row_data(i, purchases["items"][i])
            if purchases["items"][i]["status"] == utils.PurchaseStatus.UNAUDITED:
                action_buttons.append({"text": "编辑", "callback": self.edit_purchase})
                action_buttons.append({"text": "删除", "callback": self.delete_purchase, "objectName": "deleteButton"})
            else:
                action_buttons.append({"text": "查看", "callback": self.edit_purchase})
            self.purchase_table.add_action_buttons(i, action_buttons)
            
    def update_purchase_status(self, row, status):
        purchase_data = self.purchase_table.get_row_data(row)
        purchase = api.update_purchase(purchase_data["code"], status=status)
        if purchase:
            if purchase["status"] == utils.PurchaseStatus.UNAUDITED:
                action_buttons = [{"text": "审核", "callback": lambda row, status=utils.PurchaseStatus.AUDITED: self.update_purchase_status(row, status)}]
            elif purchase["status"] == utils.PurchaseStatus.AUDITED:
                action_buttons = [{"text": "入库", "callback": lambda row, status=utils.PurchaseStatus.RECEIVED: self.update_purchase_status(row, status)}]
            elif purchase["status"] == utils.PurchaseStatus.RECEIVED:
                action_buttons = [{"text": "退货", "callback": self.return_purchase}]
            else:
                action_buttons = []
            if purchase["status"] == utils.PurchaseStatus.UNAUDITED:
                action_buttons.append({"text": "编辑", "callback": self.edit_purchase})
                action_buttons.append({"text": "删除", "callback": self.delete_purchase, "objectName": "deleteButton"})
            else:
                action_buttons.append({"text": "查看", "callback": self.edit_purchase})
            self.purchase_table.set_row_data(row, purchase)
            self.purchase_table.add_action_buttons(row, action_buttons)
        

    def load_data(self):
        rs = api.get_suppliers("", page=0)
        if rs["count"] > 0:
            self.suppliers = rs["items"]
            self.supplier_input.clear()
            self.supplier_input.setItems({"全部供货商": "", **{supplier["name"]:supplier["id"] for supplier in self.suppliers}})
        self.flush_table()


class ReturnPurchaseDialog(BaseDialog):
    def __init__(self, parent, purchase_code):
        super().__init__(parent)
        self.purchase_data = api.get_purchase(purchase_code)
        self.return_items = []  # 存储要退货的商品项目
        self.reason = ""
        self.setup_ui()
        
    def setup_ui(self):
        self.setWindowTitle("采购退货")
        self.setMinimumWidth(800)
        
        layout = QVBoxLayout(self)
        
        # 采购单信息显示
        info_group = QGroupBox("采购单信息")
        info_layout = QHBoxLayout(info_group)
        
        # 显示采购单基本信息
        info_layout.addWidget(QLabel("采购单号:"))
        info_layout.addWidget(QLabel(self.purchase_data["code"]))
        info_layout.addStretch()
        
        info_layout.addWidget(QLabel("供应商:"))
        info_layout.addWidget(QLabel(self.purchase_data["supplier"]["name"]))
        info_layout.addStretch()
        
        info_layout.addWidget(QLabel("总金额:"))
        info_layout.addWidget(QLabel(f"{self.purchase_data['total_price']}{config.CURRENCY_UNIT}"))
        info_layout.addStretch()

        info_layout.addWidget(QLabel("该单已退货金额:"))
        returned_amount_label = QLabel()
        info_layout.addWidget(returned_amount_label)

        
        layout.addWidget(info_group)
        
        # 商品列表（支持多选）
        items_group = QGroupBox("商品列表（请选择要退货的商品）")
        items_layout = QHBoxLayout(items_group)
        
        # 创建商品表格
        self.items_table = CommonTableWidget(self, PURCHASE_RETURN_ITEMS_HEADER_COLUMNS, 'none')
        self.items_table.setSelectionMode(QTableWidget.SelectionMode.MultiSelection)
        
        items_layout.addWidget(self.items_table)
        layout.addWidget(items_group)
        
        # 退货信息输入
        return_group = QGroupBox("退货信息")
        return_layout = QGridLayout(return_group)

        # 当前退款单退款金额        
        self.total_return_price_label = QLabel(f"0.00({config.CURRENCY_UNIT})")
        return_layout.addWidget(QLabel("合计退款:"), 0, 0)
        return_layout.addWidget(self.total_return_price_label, 0, 1)
        # 退货原因
        self.reason_combo = NormalComboBox()
        self.reason_combo.setItems(["质量问题", "数量不符", "品种错误", "其他原因"])
        self.reason_combo.currentIndexChanged.connect(self.on_reason_changed)
        return_layout.addWidget(QLabel("退货原因:"), 1, 0)
        return_layout.addWidget(self.reason_combo, 1, 1)
        
        # 备注
        self.remark_input = NormalTextEdit(self, 200)
        self.remark_input.setPlaceholderText("请输入详细退货原因...")
        self.remark_input.setMaximumHeight(100)
        self.remark_input.setEnabled(False)
        return_layout.addWidget(QLabel("备注:"), 2, 0)
        return_layout.addWidget(self.remark_input, 2, 1)
        
        layout.addWidget(return_group)
        
        # 按钮布局
        button_layout = self.create_button_layout(self.validate_and_accept)
        layout.addLayout(button_layout)
    
        already_returned = {}  #已经退掉的数量键是product_id, 值是退款数量
        total_returned_amount = 0
        for item in api.get_purchase_returns(self.purchase_data["id"]):
            for return_item in item["items"]:
                product_id = return_item["purchaseItem"]["product_id"]
                if product_id not in already_returned:
                    already_returned[product_id] = 0
                already_returned[product_id] += return_item["quantity"]
            total_returned_amount += item["total_price"]
        returned_amount_label.setText(f"{total_returned_amount}{config.CURRENCY_UNIT}")
        #table_items = []
        self.items_table.setRowCount(len(self.purchase_data["items"]))
        for i, item in enumerate(self.purchase_data["items"]):
            if item["product_id"] not in already_returned:
                item["quantity_available"] = item["quantity"]
                item["quantity_returned"] = 0
                item["return_price"] = 0
            else:
                item["quantity_available"] = item["quantity"] - already_returned[item["product_id"]]
                item["quantity_returned"] = already_returned[item["product_id"]]
                item["return_price"] = 0
            #table_items.append(item)
            self.items_table.set_row_data(i, item)
            spinbox = NormalIntSpinBox()
            spinbox.setValue(0)
            spinbox.setRange(0, item["quantity_available"])
            spinbox.valueChanged.connect(lambda value, row=i: self.update_return_price(row, value))
            self.items_table.setCellWidget(i, len(PURCHASE_RETURN_ITEMS_HEADER_COLUMNS)-2, spinbox)

    def on_reason_changed(self):
        self.remark_input.setEnabled(self.reason_combo.currentIndex() == self.reason_combo.count() - 1)

    def update_return_price(self, row, value):
        row_data = self.items_table.get_row_data(row)
        row_data["current_quantity_returned"] = value
        row_data["return_price"] = row_data["unit_price"] * value
        self.items_table.update_row_data(row, row_data)
        self.items_table.fresh_item(row, len(PURCHASE_RETURN_ITEMS_HEADER_COLUMNS)-1)
        total_return_price = 0
        for i in range(self.items_table.rowCount()):
            total_return_price += self.items_table.get_row_data(i)["return_price"]
        self.total_return_price_label.setText(f"{total_return_price:.2f}({config.CURRENCY_UNIT})")
    
    def validate_and_accept(self):
        """验证并接受退货"""
        # 获取选中的商品
        selected_items = []
        for row in range(self.items_table.rowCount()):
            row_data = self.items_table.get_row_data(row)
            if row_data.get("current_quantity_returned", 0) > 0:
                selected_items.append({
                    "purchase_item_id": row_data["id"],
                    "quantity": row_data["current_quantity_returned"],
                    "unit_price": row_data["unit_price"],
                    "product": row_data["product"]
                })
        if not selected_items:
            MessageOverlay.warning(self, "请至少选择一个商品进行退货")
            return
        self.reason = self.reason_combo.currentText() if self.reason_combo.currentIndex() != self.reason_combo.count() - 1 \
                        else self.remark_input.toPlainText()
        self.return_items = selected_items
        
        if MessageOverlay.question(self, "确定提交", f"提交退货将不可撤消。是否提交以下退货内容:\n"
            f"{'\n'.join([f'{item['product']['name']}\t{item['quantity']}{item['product']['unit']}' for item in selected_items])}"
            f"\n共计: {sum([item['quantity'] * item['unit_price'] for item in selected_items])}({config.CURRENCY_UNIT})") == MessageOverlay.ACCEPTED:
            self.accept()


class AddPurchaseDialog(BaseDialog):
    def __init__(self, parent=None, purchase_code=None, suppliers=[]):
        super().__init__(parent)
        self.current_edit_row = -1
        self.purchase_data = api.get_purchase(purchase_code) if purchase_code else None
        self.suppliers = suppliers
        self.purchase_items = []
        self.setup_ui()
        
        if self.purchase_data:
            self.load_purchase_data()
    
    def update_total(self):
        quantity = self.quantity_input.value()
        price = self.price_input.value()
        total = quantity * price
        self.total_input.setText(f"{total:.2f}")
    
    def validate_and_accept(self):
        if not self.code_input.text():
            MessageOverlay.warning(self, "请输入采购单号")
            return
        
        if not self.product_input.text():
            MessageOverlay.warning(self, "请输入商品名称")
            return
        
        if self.quantity_input.value() <= 0:
            MessageOverlay.warning(self, "数量必须大于0")
            return
        
        self.accept()
        self.setup_ui()
        
    def setup_ui(self):
        # 根据模式设置窗口标题
        self.setWindowTitle("编辑采购单" if self.purchase_data else "添加采购单")
        self.setMinimumWidth(900)  # 增加宽度以容纳左右两侧布局
        self.setMinimumHeight(450)
        
        main_layout = QHBoxLayout(self)  # 主布局改为水平布局
        
        # 左侧 - 采购单基本信息和商品添加表单
        left_widget = QWidget()
        left_layout = QVBoxLayout(left_widget)
        
        # 采购单基本信息
        basic_info_group = QGroupBox("采购单基本信息")
        basic_info_layout = QGridLayout(basic_info_group)
        
        # 采购单号
        self.code_input = NormalLineEdit()
        self.code_input.setReadOnly(True)
        basic_info_layout.addWidget(QLabel("采购单号:"), 0, 0)
        basic_info_layout.addWidget(self.code_input, 0, 1)
        
        # 供应商
        self.supplier_input = NormalComboBox()
        supplier_items= {"选择后清空列表并自动添加低库存)" : ""}
        supplier_items.update({supplier["name"]:supplier["id"] for supplier in self.suppliers})
        self.supplier_input.setItems(supplier_items)
        if self.purchase_data:
            self.supplier_input.setCurrentText(self.purchase_data["supplier"]["name"])
            self.supplier_input.setEnabled(False)
        self.supplier_input.currentIndexChanged.connect(self.on_supplier_selected)
        basic_info_layout.addWidget(QLabel("供应商:"), 1, 0)
        basic_info_layout.addWidget(self.supplier_input, 1, 1)
        
        # 状态
        self.status_label = NormalLabel(utils.PurchaseStatus(self.purchase_data["status"]).description if
                                        self.purchase_data else utils.PurchaseStatus.UNAUDITED.description)
        basic_info_layout.addWidget(QLabel("状态:"), 2, 0)
        basic_info_layout.addWidget(self.status_label, 2, 1)

        basic_info_layout.addWidget(QLabel("开单时间:"), 3, 0)
        basic_info_layout.addWidget(NormalLabel(utils.format_datetime(self.purchase_data["created_at"])
                                    if self.purchase_data else datetime.now().strftime("%Y-%m-%d")), 3, 1)

        if self.purchase_data:
            basic_info_layout.addWidget(QLabel("最后更新时间:"), 4, 0)
            basic_info_layout.addWidget(NormalLabel(utils.format_datetime(self.purchase_data["updated_at"])), 4, 1)

        left_layout.addWidget(basic_info_group)
        
        # 商品添加表单
        item_group = QGroupBox("添加商品")
        item_layout = QGridLayout(item_group)
        
        # 商品名称
        self.product_input = AutoCompleteLineEdit(self.get_product_list, placeholder_text="搜索商品名称或编码")
        self.product_input.setReadOnly(self.supplier_input.currentData() == "")
        self.product_input.selectedChanged.connect(self.on_product_selected)
        item_layout.addWidget(QLabel("商品名称:"), 0, 0)
        item_layout.addWidget(self.product_input, 0, 1)
        
        # 数量
        self.quantity_input = NormalIntSpinBox()
        self.quantity_input.setValue(1)  # 默认数量为1
        item_layout.addWidget(QLabel("数量:"), 1, 0)
        item_layout.addWidget(self.quantity_input, 1, 1)
        
        # 单价
        self.price_input = NormalFloatSpinBox()
        self.price_input.setReadOnly(True)
        item_layout.addWidget(QLabel("单价:"), 2, 0)
        item_layout.addWidget(self.price_input, 2, 1)
        
        # 总金额
        self.total_input = NormalFloatSpinBox()
        self.total_input.setReadOnly(True)
        item_layout.addWidget(QLabel("总金额:"), 3, 0)
        item_layout.addWidget(self.total_input, 3, 1)
        
        # 添加商品按钮
        button_layout = QHBoxLayout()
        self.add_item_btn = BluePushButton("添加到采购列表")
        self.add_item_btn.clicked.connect(self.add_item_to_list)
        self.cancel_edit_btn = WhitePushButton("取消编辑")
        self.cancel_edit_btn.setVisible(False)
        self.cancel_edit_btn.clicked.connect(self.cancel_edit)
        button_layout.addWidget(self.add_item_btn)
        button_layout.addWidget(self.cancel_edit_btn)
        item_layout.addLayout(button_layout, 4, 0, 1, 2, Qt.AlignCenter)
        
        left_layout.addWidget(item_group)
        left_layout.addStretch()
        
        # 右侧 - 采购列表预览
        right_widget = QWidget()
        right_layout = QVBoxLayout(right_widget)
        
        # 采购列表标题
        right_layout.addWidget(QLabel("采购列表预览"))
        
        # 采购列表表格
        self.items_table = CommonTableWidget(self, PURCHASE_ITEMS_HEADER_COLUMNS, 'none')
        right_layout.addWidget(self.items_table)
        
        # 总计信息
        total_widget = QWidget()
        total_layout = QHBoxLayout(total_widget)
        total_layout.addStretch()
        total_layout.addWidget(QLabel("商品总数:"))
        self.total_items_label = QLabel("0")
        total_layout.addWidget(self.total_items_label)
        total_layout.addWidget(QLabel("总金额:"))
        self.total_amount_label = QLabel("0.00")
        total_layout.addWidget(self.total_amount_label)
        #total_layout.addStretch()
        right_layout.addWidget(total_widget)
        
        # 创建保存按钮布局并添加到右侧布局底部
        button_layout = self.create_button_layout(self.validate_and_accept)
        right_layout.addLayout(button_layout)
        
        # 添加左右两侧到主布局
        main_layout.addWidget(left_widget, 1)  # 左侧占比1
        main_layout.addWidget(right_widget, 2)  # 右侧占比2

        self.quantity_input.valueChanged.connect(self.update_total)
        if self.purchase_data:
            self.code_input.setText(self.purchase_data["code"])
            if self.purchase_data["status"] != utils.PurchaseStatus.UNAUDITED:
                self.product_input.setReadOnly(True)
                self.add_item_btn.setEnabled(False)
                self.items_table.setColumnHidden(len(PURCHASE_ITEMS_HEADER_COLUMNS)-1, True)
        else:
            self.code_input.setText("自动生成")

    def get_product_list(self, keyword):
        if keyword:
            return api.get_supplier_products_by_search(self.supplier_input.currentData(), keyword)
        else:
            self.price_input.setValue(0)
            self.total_input.setValue(0)
            return []
        
    def update_total(self):
        quantity = self.quantity_input.value()
        price = self.price_input.value()
        total = quantity * price
        self.total_input.setValue(total)

    def on_product_selected(self, product):
        price = product["price"]
        self.price_input.setValue(price)
        self.total_input.setValue(price * self.quantity_input.value())
    
    def add_item_to_list(self):
        """添加商品到采购列表"""
        quantity = self.quantity_input.value()
        
        # 如果是编辑模式，更新现有行
        if self.current_edit_row >= 0:
            if quantity <= 0:
                self.delete_item(self.current_edit_row)
                return
            item_data = self.items_table.get_row_data(self.current_edit_row)
            item_data.update({
                "quantity": quantity,
                "total_price": Decimal(self.total_input.value()),
            }) #这里是值引用，所以purchase_items也会更改
            #self.items_table.set_row_data(self.current_edit_row, item_data)
            self.product_input.setReadOnly(False)
            self.current_edit_row = -1
            self.add_item_btn.setText("添加到采购列表")
            self.cancel_edit_btn.setVisible(False)
            self.add_item_btn.parent().setTitle("添加商品")
        else:
            selected_product = self.product_input.get_selected_item()
            if not selected_product:
                MessageOverlay.warning(self, "请选择商品")
                self.product_input.setFocus()
                return
            if quantity <= 0:
                MessageOverlay.warning(self, "数量必须大于0")
                self.quantity_input.setFocus()
                return
            
            for item in self.purchase_items:
                if item["product"]["id"] == selected_product["id"]:
                    item["quantity"] += quantity
                    item["total_price"] += Decimal(self.total_input.value())
                    break
            else:
                if len(self.purchase_items) >= config.PURCHASE_MAX_PRODUCT_COUNT:
                    MessageOverlay.warning(self, f"采购单最多只能包含{config.PURCHASE_MAX_PRODUCT_COUNT}种商品")
                    return
                self.purchase_items.append({
                    "product": selected_product,
                    "quantity": quantity,
                    "cost_price": Decimal(self.price_input.value()),
                    "total_price": Decimal(self.total_input.value()),
                })
        
        # 清空输入框
        self.product_input.clear()
        self.quantity_input.setValue(1)
        self.price_input.setValue(0)
        self.total_input.setValue(0)
        self.refresh_items_table()
    
    def edit_item(self, row):
        """编辑采购列表中的商品"""
        if row < 0 or row >= len(self.purchase_items):
            return
        
        item = self.items_table.get_row_data(row)
        self.product_input.setText(item["product"]["name"])
        self.product_input.setReadOnly(True)
        self.quantity_input.setValue(item["quantity"])
        self.price_input.setValue(item["unit_price"])
        self.total_input.setValue(item["total_price"])
        
        # 标记当前正在编辑的行
        self.current_edit_row = row
        self.add_item_btn.setText("更新商品")
        self.cancel_edit_btn.setVisible(True)
        self.add_item_btn.parent().setTitle("更新商品")

    def cancel_edit(self):
        self.product_input.setReadOnly(False)
        self.current_edit_row = -1
        self.add_item_btn.setText("添加到采购列表")
        self.cancel_edit_btn.setVisible(False)
        self.add_item_btn.parent().setTitle("添加商品")

    def delete_item(self, row):
        """删除采购列表中的商品"""
        if row < 0 or row >= len(self.purchase_items):
            return
        
        if MessageOverlay.question(self, "确认移除", "确定要移除这个商品吗(在保存之前并不会修改此采购单)？") == MessageOverlay.ACCEPTED:
            del self.purchase_items[row]
            self.refresh_items_table()
    
    def refresh_items_table(self):
        """刷新采购列表表格"""
        if not self.purchase_items:
            self.items_table.setRowCount(0)
            return
        self.items_table.setRowCount(len(self.purchase_items))
        
        total_items = 0
        total_amount = Decimal(0)
        
        for row, item in enumerate(self.purchase_items):
            self.items_table.set_row_data(row, item)
            self.items_table.add_action_buttons(row, [{"text": "修改", "callback": self.edit_item},
                {"text": "移除", "callback": self.delete_item, "objectName": "deleteButton"}])

            total_items += item["quantity"]
            total_amount += item["total_price"]
        
        self.total_items_label.setText(str(total_items))
        self.total_amount_label.setText(f"{total_amount:.2f}")
    
    def load_purchase_data(self):
        # 设置基本信息
        self.code_input.setText(self.purchase_data["code"])
        self.supplier_input.setCurrentText(self.purchase_data["supplier"]["name"])
        
        self.purchase_items = self.purchase_data["items"]
        self.refresh_items_table()

    def on_supplier_selected(self):
        self.supplier_input.model().item(0).setEnabled(False)
        products = api.generate_supplier_low_stock_products(self.supplier_input.currentData())
        self.purchase_items = []
        for product in products[:config.PURCHASE_MAX_PRODUCT_COUNT]:
            self.purchase_items.append({
                "product": product,
                "quantity": 1,
                "cost_price": product["cost_price"],
                "total_price": product["cost_price"],
            })
        self.refresh_items_table()
        self.product_input.setReadOnly(False)

    def validate_and_accept(self):        
        if not self.supplier_input.currentData():
            MessageOverlay.warning(self, "请选择供应商")
            return
        self.accept()

    @property
    def supplier_id(self):
        return self.supplier_input.currentData()